package cn.zjk.test.bean;

import cn.zjk.springframework.beans.BeansException;
import cn.zjk.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zjk
 * @CreateTime 2023/3/30 23:59
 */
public class ProxyBeanFactory implements FactoryBean<IUserDao> {
    @Override
    public IUserDao getObject() throws BeansException {
        InvocationHandler handler = (proxy,method,args)->{
            //添加排除方法
            if("toString".equals(method.getName())){
                return this.toString();
            }else{
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("001", "zjk");
                hashMap.put("002", "z");
                hashMap.put("003", "j");
                hashMap.put("004", "k");
                return "你被代理了 " + method.getName() + "：" + hashMap.get(args[0].toString());
            }
        };
        return (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IUserDao.class},handler);
    }

    @Override
    public Class<?> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
